// components/imgUpload/imgUpload.js
const app = getApp();
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';

Component({
  /**
   * 组件的属性列表
   */
  properties: { 
    //上传地址   
    uploadFileUrl: {
      type: String,
      value: 'https://sys.bangnikeji.net/oss/headImgUpload?filepath=bangni/images/'
    },

    //可以选择的图片张数，最多9张
    count: {
      type: Number,
      value: 9
    },

    //边框颜色
    borderColor:{
      type: String,
      value:'#ddd'
    },
    
    //传来的图片列表
    imgUrls:{
      type: Array,
      value: []
    }
  },

  options: {    
    //虚拟的，这样可以不作用样式
    virtualHost: true    
  },

  /**
   * 组件的初始数据
   */
  data: {
    //图片列表
    imageList:[],
    //是否是单一图片
    isOne:false,
    //单一图片的路径
    oneUrl:'',
    //是否显示添加图标
    showIcon:true  
  },
  
  lifetimes:{
    attached(){
      if(this.properties.count==1){
        this.setData({ 
          isOne: true
        })
      }

      setTimeout(() => {        
        this.setData({ 
          imageList: this.properties.imgUrls
        })        
      }, 1000);  
    }
  }, 

  /**
   * 组件的方法列表
   */
  methods: {    
    //选择图片并上传
    onChooseImage: function () {
      var _this = this;
      wx.chooseImage({
        sourceType: ['album', 'camera'],
        sizeType:['compressed'],
        count:this.properties.count,
        success: function (res) {        
          let imgs = res.tempFilePaths;
          let promiseArr=[];        
          Toast.loading({
            duration: 0,
            forbidClick: true,          
            message: '图片上传中...'
          });
          for (let i = 0; i < imgs.length; i++) {
            let pro=new Promise(function(resolve,reject){            
              wx.uploadFile({
                url: _this.properties.uploadFileUrl,
                filePath: imgs[i],
                name: 'file',
                success(res) {                                 
                  let imgUrl = JSON.parse(res.data).data;                  
                  if(imgUrl.indexOf("?")!=-1){
                    let index = imgUrl.indexOf("?");
                    if (index != -1) {
                      imgUrl = imgUrl.substring(0, index); 
                    }
                  }                               
                  resolve(imgUrl);
                }, 
                fail(){
                  Toast('上传失败请重试');               
                }              
              });
            });          
            promiseArr.push(pro); 
          }

          Promise.all(promiseArr).then(item => {
            Toast.clear();

            if(_this.data.isOne){
              _this.setData({
                imageList: item,
                showIcon: false
              })

            }else{
              _this.setData({
                imageList: _this.data.imageList.concat(item)
              })
            }            

            //把图片路径传给父页面
            _this.getUploadUrl();

          }).catch((error) => {
            Toast('上传失败请重试');           
          });
                       
        }
      })
    },


    //预览图片
    onPreviewImage: function (e) {
      var current = e.target.dataset.src
      wx.previewImage({
        current: current,
        urls: this.data.imageList 
      })
    },


    //删除图片
    onDeleteFile(e){    
      let imgUrl = e.currentTarget.dataset.detail;    
      let list = this.data.imageList;
      list = list.filter((item,index)=>{
        return item != imgUrl;
      }); 

      this.setData({ 
        imageList: list 
      }); 

      //把图片路径传给父页面
      this.getUploadUrl();
    },


    //把图片路径传给父页面
    getUploadUrl(){
      this.triggerEvent('getUploadUrl', this.data.imageList);
    }

  }
})
